/**
 * 
 */
package cc.rico.sync;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;

import cc.rico.api.BaseZK;
import cc.rico.utils.ZkUtil;

/**
 * @author rico 2016年8月20日
 *
 */
public class ZkSync extends BaseZK implements Watcher {
	private static final String SYNC_PATH = "/sync";
	private ZooKeeper zk = null;
	
	public ZkSync() {
		zk = ZkUtil.getInstance(this);
	}
	
	/**
	 * 同步数据
	 * @param data
	 */
	public void syncData(String data) {
		try {
			if(zk.exists(SYNC_PATH, null) != null) {
				zk.setData(SYNC_PATH, data.getBytes(), -1);
				
			} else {
				zk.create(SYNC_PATH, data.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
			}
		} catch (KeeperException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	public void close() {
		ZkUtil.close(zk);
	}

	@Override
	public void process(WatchedEvent event) {
		logger.info("connection to zk successfully...");
	}
	
}
